import Vue from "vue";
import VueRouter from "vue-router";
import Login from "../views/Login.vue";
import Index from "../views/Index.vue";

Vue.use(VueRouter);
const originalPush = VueRouter.prototype.push;

VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

const routes = [
  {
    path: "/",
    name: "login",
    component: Login,
  },

  {
    path: "/register",
    name: "register",
    component: () => import("../views/Register.vue"),
    meta: {
      requireAuth: true,
    },
  },

  {
    path: "/index",
    name: "index",
    component: Index,
    meta: {
      requireAuth: true,
    },
    // redirect意味着重定向，当浏览器跳转到/studentindex时将会自动重定向到/StudentIndex/container
    redirect: "/index/one",
    children: [
      {
        path: "one",
        name: "one",
        component: () => import("../views/Home.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "two",
        name: "two",
        component: () => import("../views/Company.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "three",
        name: "three",
        component: () => import("../views/User.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "four",
        name: "four",
        component: () => import("../views/Carousel.vue"),
        meta: {
          requireAuth: true,
        },
      },
      {
        path: "hot",
        name: "hot",
        component: () => import("../views/Hot.vue"),
        meta: {
          requireAuth: true,
        },
      },
    ],
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
// 路由守卫
router.beforeEach((to, from, next) => {
  console.log(sessionStorage.getItem("uname"));
  console.log(to.meta.requireAuth);
  if (to.meta.requireAuth) {
    if (sessionStorage.getItem("uname")) {
      next();
    } else {
      alert("请先登录");
      next({ path: "/" });
    }
  }
  next();
});
export default router;
